/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace lcc {

export namespace fs {

const TAG = "lcc/utils/fs.ts";

const Fs = require('fs');
const Path = require("path");

/**
 * @zh
 * 查找文件类型
 */
export enum FindFileType {
    /**
     * @zh
     * 文件
     */
    FILE = 1,
    
    /**
     * @zh
     * 目录
     */
	DIRECTORY,
}

/**
 * @zh
 * 在指定目录中查找文件
 * 
 * @param dir - 目录路径
 * @param filename - 文件名
 * @param types - 查找类型，多种类型可以用`|`连接， 比如`FindFileType.FILE | FindFileType.DIRECTORY`
 */
export function findFile(dir:string, filename:string, types:number = FindFileType.FILE | FindFileType.DIRECTORY){
	for(let file of Fs.readdirSync(dir)){
		let npath = Path.join(dir, file);
		var info = Fs.statSync(npath);
		if((file == filename) && (info.isDirectory() ? types & FindFileType.DIRECTORY : types & FindFileType.FILE)){
			return npath;
		}else if(info.isDirectory()){
			let result = findFile(npath, filename, types);
			if(result){
				return result;
			}
		}
	}
}

/**
 * @zh
 * 遍历目录路径
 * 
 * @param path_ 遍历的目录路径
 * @param callback 遍历回调函数，如果回调函数返回true，则停止遍历
 */
export function mapDirectory(path_:string, callback:(path:string, file:string, isdir:boolean)=>boolean) {
	for(let file of Fs.readdirSync(path_)){
		let npath = Path.join(path_, file);
		var info = Fs.statSync(npath);
		if(callback(npath, file, info.isDirectory())){
			return true;
		}else if(info.isDirectory()){
			if(mapDirectory(npath, callback)){
				return true;
			}
		}
	}
}

/**
 * @zh
 * 复制文件
 * 
 * @param srcPath - 源文件路径
 * @param destPath - 目的文件路径
 */
export function copyFile(srcPath:string, destPath:string){
	Fs.writeFileSync(destPath, Fs.readFileSync(srcPath));
}

/**
 * @zh
 * 复制目录
 * 
 * @param src - 源目录路径
 * @param dest - 目的目录路径
 */
export function copyDirectory(srcPath:string, destPath:string){
    if(Fs.existsSync(srcPath)){
        if(!Fs.existsSync(destPath)){
            Fs.mkdirSync(destPath, { recursive : true });
        }
        for(let file of Fs.readdirSync(srcPath)){
            let spath = Path.join(srcPath, file);
            let dpath = Path.join(destPath, file);
            var info = Fs.statSync(spath);
            if(info.isDirectory()){
                copyDirectory(spath, dpath);
            }else{
                copyFile(spath, dpath);
            }
        }
    }
}

/**
 * @zh
 * 清空目录
 * 
 * @param path - 路径
 */
export function clearDirectory(path:string){
    if(Fs.existsSync(path)){
        Fs.readdirSync(path).forEach((file:string) => {
            let curPath = path + "/" + file;
            if(Fs.statSync(curPath).isDirectory()){
                clearDirectory(curPath);
				Fs.rmdirSync(curPath);
            } else {
                Fs.unlinkSync(curPath);
            }
        });
    }
}

/**
 * @zh
 * 移除目录
 * 
 * @param path - 路径
 */
export function removeDirectory(path:string){
    if(Fs.existsSync(path)){
		clearDirectory(path);
		Fs.rmdirSync(path);
    }
}

/**
 * @zh
 * TSL文件配置
 */
export interface TSLFilesConfig {
    /**
     * @zh
     * key文件
     */
    key:string;

    /**
     * @zh
     * 证书文件
     */
    cert:string;

    /**
     * @zh
     * 密码
     */
    password?:string;
}

/**
 * @zh
 * 读取TSL配置
 * 
 * @param ftsl - TSL文件配置
 * @param baseDir - 基础目录
 */
export function readTSLConf(ftsl:TSLFilesConfig, baseDir?:string):TSLConfig{
    if(baseDir){
        ftsl.key = Path.join(baseDir, ftsl.key);
        ftsl.cert = Path.join(baseDir, ftsl.cert);
    }
    return {
        key:Fs.readFileSync(ftsl.key),
        cert:Fs.readFileSync(ftsl.cert),
        passphrase : ftsl.password,
    }
}

}

}
